package com.syqc.monitor.popup

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.syqc.comlib.utils.copyText
import com.syqc.entity.Driver
import com.syqc.monitor.R
import com.syqc.monitor.databinding.PopupDriversBinding
import com.syqc.utils.ToolsUtil

/**
 *@Author Jasper
 *@Time   2020/9/21
 *@Desc
 */
class DriversPopup(val context: Context) : PopupWindow(context) {

    private val binding = PopupDriversBinding.inflate(LayoutInflater.from(context))
    private val mAdapter by lazy { DriverAdapter() }

    init {
        contentView = binding.root
        initView()
        isFocusable = true //popupwindow设置焦点
        isClippingEnabled = false //设置是否裁剪内容
        setBackgroundDrawable(ColorDrawable(-0x56000000)) //设置背景
//        isOutsideTouchable = true //点击外面窗口消失
        width = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的宽
        height = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的高
    }

    private fun initView() {
        binding.ivClose.setOnClickListener { dismiss() }
        binding.rvDrivers.layoutManager = LinearLayoutManager(context)
        binding.rvDrivers.adapter = mAdapter
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            ToolsUtil.talkPhone(context, mAdapter.data[position].driverPhone)
        }
        mAdapter.setOnItemLongClickListener { adapter, view, position ->
            val driver = mAdapter.data[position]
            if (driver.driverPhone.isNullOrEmpty()) {
                copyText("${driver.driverName}", context)
            } else {
                copyText("${driver.driverName} : ${driver.driverPhone}", context)
            }
            true
        }
    }

    fun show(view: View, data: MutableList<Driver>) {
        mAdapter.setList(data)
        showAtLocation(view, Gravity.NO_GRAVITY, 0, 0)
    }

}

class DriverAdapter : BaseQuickAdapter<Driver, BaseViewHolder>(R.layout.item_driver) {
    init {
        addChildClickViewIds(R.id.ivPhone)
    }

    override fun convert(holder: BaseViewHolder, item: Driver) {
        holder.setText(R.id.tvDrvName, item.driverName ?: "")
        holder.setText(R.id.tvDrvPhone, item.driverPhone ?: "")
        holder.setVisible(R.id.ivPhone, !item.driverPhone.isNullOrEmpty())
    }
}